﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace PhotoGallery.Models.Utils
{
    public class FileValidation
    {
        public static bool IsValid(object value, List<string> validExtensions)
        {
            HttpPostedFileBase file = value as HttpPostedFileBase;
            validExtensions.ForEach(x=> x = x.ToUpper());
            List<string> extentions = new List<string>();
            foreach (string s in validExtensions)
            {
                extentions.Add(s.ToUpper());
            }
            if (file != null)
            {
                var fileName = file.FileName.ToUpper();
                var isValidExtension = extentions.Any(y => fileName.EndsWith(y));
                return isValidExtension;
            }
            return true;
        }
    }

    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
    public class FileExtensionsAttribute : ValidationAttribute
    {
        private List<string> ValidExtensions { get; set; }

        public FileExtensionsAttribute(string fileExtensions)
        {
            ValidExtensions = fileExtensions.Split('|').ToList();
        }

        public override bool IsValid(object value)
        {
            HttpPostedFileBase file = value as HttpPostedFileBase;
            if (file != null)
            {
                var fileName = file.FileName;
                var isValidExtension = ValidExtensions.Any(y => fileName.EndsWith(y));
                return isValidExtension;
            }
            return true;
        }
    }
}